package com.basic.business.store.service.impl;

import com.basic.business.common.constants.Constants;
import com.basic.business.common.redis.RedisCacheUtils;
import com.basic.business.common.utils.StringUtils;
import com.basic.business.store.domain.TStoreMgmt;
import com.basic.business.store.mapper.ITStoreMgmtMapper;
import com.basic.business.store.service.ITStoreMgmtService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺管理表服务实现类
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TStoreMgmtServiceImpl implements ITStoreMgmtService {

    @Resource
    private ITStoreMgmtMapper tStoreMgmtMapper;

    /**
     * 项目启动时，初始化店铺信息缓存
     */
    @PostConstruct
    public void init(){
        resetStoreCache();
    }

    @Override
    public List<TStoreMgmt> getNormalStoreInfo() {
        return tStoreMgmtMapper.getNormalStoreInfo();
    }

    /**
     * 重置店铺信息缓存
     */
    private void resetStoreCache() {
        // 清空缓存
        RedisCacheUtils.clearCache(Constants.STORE_REDIS_KEY + "*");
        // 加载缓存
        loadingStoreCache();
    }

    /**
     * 加载店铺信息缓存
     */
    private void loadingStoreCache() {

        // 处理ID映射
        Map<String, TStoreMgmt> storeMap = getNormalStoreInfo().stream()
                .collect(Collectors.toMap(TStoreMgmt::getId,store -> store,(existing, replacement) -> existing)); // 处理键冲突，保留已有值

        // 处理账单号映射
        Map<String, TStoreMgmt> billNoMap = getNormalStoreInfo().stream()
                .filter(store -> StringUtils.isNotBlank(store.getBillNo()))
                .collect(Collectors.toMap(TStoreMgmt::getBillNo,store -> store,(existing, replacement) -> existing)); // 处理键冲突，保留已有值

        // 存储到Redis
        for (Map.Entry<String, TStoreMgmt> entry : storeMap.entrySet()) {
            RedisCacheUtils.setCacheObject(Constants.STORE_REDIS_KEY + entry.getKey(), entry.getValue());
        }

        for (Map.Entry<String, TStoreMgmt> entry : billNoMap.entrySet()) {
            RedisCacheUtils.setCacheObject(Constants.STORE_REDIS_KEY + entry.getKey(), entry.getValue());
        }

    }


}
